package com.cdtye.shuoh.controller.device;

import com.cdtye.common.webcore.web.AjaxJson;
import com.cdtye.shuoh.config.netty.ServerHandler;
import com.cdtye.shuoh.domain.constant.FrameConstants;
import com.cdtye.shuoh.domain.device.entity.Device;
import com.cdtye.shuoh.domain.device.vo.DeviceVo;
import com.cdtye.shuoh.domain.enums.DeviceConnectStatus;
import com.cdtye.shuoh.domain.enums.DeviceType;
import com.cdtye.shuoh.domain.enums.FrameType;
import com.cdtye.shuoh.domain.enums.PacketType;
import com.cdtye.shuoh.service.device.DeviceService;
import com.cdtye.shuoh.service.device.impl.DeviceServiceImpl;
import com.cdtye.shuoh.util.text.Crc16Utils;
import com.cdtye.shuoh.util.text.DataConverter;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.yeauty.annotation.PathVariable;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备管理Controller
 * @author ZhongWang Wang
 * @date 2022-12-21
 */
@RestController
@RequestMapping("/device")
public class DeviceController {
    @Autowired
    private DeviceService deviceService;

    /**
     * 新增设备管理
     * @param device
     * @return
     */
    @PostMapping("/add")
    public AjaxJson add(@RequestBody Device device) {
        try {
            System.out.println(device);
            return deviceService.insertDevice(device);
        } catch (Exception e) {
            return AjaxJson.error(e.getMessage());
        }
    }

    /**
     * 获取设备详情
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public AjaxJson getById(@PathVariable String id){
        return AjaxJson.success(deviceService.getById(id));
    }


    /**
     * 拍照反控制指令
     * @param ip
     * @param port
     * @param channelNo
     * @param presettingNo
     * @param cmdId
     */
    @GetMapping("/takePhoto")
    public void takePhoto(String ip,Integer port,Integer channelNo,Integer presettingNo,String cmdId){
        ServerHandler.channelGroup.forEach(ch->{
            InetSocketAddress insocket = (InetSocketAddress) ch.remoteAddress();
            if(insocket.getAddress().getHostAddress().equals(ip) && insocket.getPort() == port){
                String message = Crc16Utils.replaceCrcStr(FrameConstants.Sync.concat("0c00").concat(cmdId).concat(FrameType.VIDEO_CONTROL.getCode()).concat(PacketType.REQUEST_IMAGE.getCode()).concat("00")
                        .concat(DataConverter.parseInteger2Hex(channelNo,2)).concat(DataConverter.parseInteger2Hex(presettingNo,2)).concat("00000000000000000000").concat(FrameConstants.FrameTail));
                ch.writeAndFlush(message);
                System.out.println("拍照"+message);
            }
        });
    }

    /**
     * 分页查询
     * @param deviceVo
     * @return
     */
    @PostMapping("/pageList")
    public AjaxJson pageList(@RequestBody DeviceVo deviceVo){
        return AjaxJson.success(deviceService.pageList(deviceVo));
    }

    /**
     * 更新设备信息
     * @param vo
     * @return
     */
    @PostMapping("/updateDevice")
    public AjaxJson updateDevice(@RequestBody DeviceVo vo){
        return AjaxJson.success(deviceService.updateDevice(vo));
    }

    /**
     * 获取设备列表对应各个状态的设备数量
     * @return
     */
    @GetMapping("/listStatusCount")
    public AjaxJson listStatusCount(){
        Map<String, List<Device>> connectStatusCollect = deviceService.selectList(new DeviceVo()).parallelStream().collect(Collectors.groupingBy(Device::getConnectStatus));
        Map<String , Integer> countMap = new HashMap<>();
        //统计设备在线数量
        countMap.put("onlineCount", !connectStatusCollect.isEmpty()&&!CollectionUtils.isEmpty(connectStatusCollect.get(DeviceConnectStatus.ONLINE.getValue()))?connectStatusCollect.get(DeviceConnectStatus.ONLINE.getValue()).size():0);
        //统计设备离线数量
        countMap.put("offlineCount", !connectStatusCollect.isEmpty()&&!CollectionUtils.isEmpty(connectStatusCollect.get(DeviceConnectStatus.OFFLINE.getValue()))?connectStatusCollect.get(DeviceConnectStatus.OFFLINE.getValue()).size():0);
        //统计设备初始化数量
        countMap.put("initCount", !connectStatusCollect.isEmpty()&&!CollectionUtils.isEmpty(connectStatusCollect.get(DeviceConnectStatus.INIT.getValue()))?connectStatusCollect.get(DeviceConnectStatus.INIT.getValue()).size():0);
        return AjaxJson.success(countMap);

    }

    /**
     * 删除设备管理
     * @param id
     * @return
     */
    @GetMapping("/removeDevice")
    public AjaxJson removeDevice(String id){
        return AjaxJson.success(deviceService.deleteById(id));
    }

    /**
     * 校验clientId是否存在
     * @param clientId
     * @return
     */
    @GetMapping("/validationFindOneByClientId")
    public AjaxJson validationFindOneByClientId(@PathVariable String clientId){
        if(null == clientId){
            AjaxJson.error("clientId不能为空");
        }
        Device findOneByClientId = deviceService.findOneByClientId(clientId);
        if (null == findOneByClientId) {
            return AjaxJson.success("clientId可用");
        }
        return AjaxJson.error("clientId已存在");
    }

    /**
     * 校验clientId是否存在
     * @param deviceIdentification
     * @return
     */
    @GetMapping("/validationFindOneByDeviceIdentification")
    public AjaxJson validationFindOneByDeviceIdentification(@PathVariable String deviceIdentification){
        if(null == deviceIdentification){
            AjaxJson.error("deviceIdentification不能为空");
        }
        Device findOneByDeviceIdentification = deviceService.findOneByDeviceIdentification(deviceIdentification);
        if (null == findOneByDeviceIdentification) {
            return AjaxJson.success("deviceIdentification可用");
        }
        return AjaxJson.error("deviceIdentification已存在");
    }


    /**
     * 连接状态统计
     * @return
     */
    @GetMapping("/connectStatusStatistic")
    public AjaxJson connectStatusStatistic(){
        return AjaxJson.success(deviceService.connectStatusStatistic());
    }

    /**
     * 设备类型统计
     * @return
     */
    @GetMapping("/deviceTypeStatistic")
    public AjaxJson deviceTypeStatistic(){
        return AjaxJson.success(deviceService.deviceTypeStatistic());
    }

    @GetMapping("/deviceStatusStatistic")
    public AjaxJson deviceStatusStatistic(){
        return AjaxJson.success(deviceService.deviceStatusStatistic());
    }



}
